﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.Ctrls;
using EHR.Common;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;

namespace CommunitySystem.PageView.公务员选拔
{
    public partial class ExamePublishWindow : ChildWindow
    {
        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialSelectionServiceClient client = null;
        private CommunitySystem.Model.Silverlight.PublicOfficialInfo entity = null;
        private int errorCount = 0;
        public ExamePublishWindow(int id)
        {
            InitializeComponent();
            Page(null);

            client = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            client.ChechIsPublishCompleted += new EventHandler<PublicOfficialSelectionService.ChechIsPublishCompletedEventArgs>(client_ChechIsPublishCompleted);
            client.SavePublicOfficialInfoCompleted += new EventHandler<PublicOfficialSelectionService.SavePublicOfficialInfoCompletedEventArgs>(client_SavePublicOfficialInfoCompleted);
            client.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(client_UploadFileCompleted);
            client.UploadStringCompleted += new EventHandler<PublicOfficialSelectionService.UploadStringCompletedEventArgs>(client_UploadStringCompleted);
            client.ShiFouYouFaBuZhiWeiCompleted += new EventHandler<PublicOfficialSelectionService.ShiFouYouFaBuZhiWeiCompletedEventArgs>(client_ShiFouYouFaBuZhiWeiCompleted);
            this.BindingValidationError += (sender, e) =>
            {
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    errorCount++;
                }
                else if (e.Action == ValidationErrorEventAction.Removed)
                {
                    errorCount--;
                }
            };
            client.GetPublicOfficialInfoCompleted += new EventHandler<PublicOfficialSelectionService.GetPublicOfficialInfoCompletedEventArgs>(client_GetPublicOfficialInfoCompleted);
            if (id > 0)
            {
                client.GetPublicOfficialInfoAsync("id = " + id);
            }
            else
            {
                entity = new Model.Silverlight.PublicOfficialInfo() { InputName = Session.LoginUser.LoginName };
                this.DataContext = entity;
                SetExameType(entity);
            }
        }

        

        void client_UploadStringCompleted(object sender, PublicOfficialSelectionService.UploadStringCompletedEventArgs e)
        {
            UploadFileInfo info = e.UserState as UploadFileInfo;
            if (info.UploadString.Count == 0)
            {
                client.SavePublicOfficialInfoAsync(_entity, listfiles, info.Name);
            }
            else
            {
                client.UploadStringAsync(info.Name, info.UploadString[0], false, info);
                info.UploadString.RemoveAt(0);
            }
        }

        void client_SavePublicOfficialInfoCompleted(object sender, PublicOfficialSelectionService.SavePublicOfficialInfoCompletedEventArgs e)
        {
            if (e.Result)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                this.DialogResult = true;
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存失败");
            }
        }

        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo serviceEntity = null;
        private List<CommunitySystem.PublicOfficialSelectionService.Files> GetFiles = null;
      
        void client_GetPublicOfficialInfoCompleted(object sender, PublicOfficialSelectionService.GetPublicOfficialInfoCompletedEventArgs e)
        {
            serviceEntity = e.Result.FirstOrDefault();
            _orgs = serviceEntity.Orgs;
            if (serviceEntity != null)
            {
                entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert<Model.Silverlight.PublicOfficialInfo>(serviceEntity);
                this.DataContext = entity;
                SetExameType(entity);
                client.GetFilesCompleted += (sender1, e1) =>
                {
                    if (e1.Result.Count > 0)
                    {
                        GetFiles = e1.Result.ToList();
                        Page(null);
                        //foreach (var c in e1.Result)
                        //{
                        //    UploadFileInfo upf = new UploadFileInfo() { FilesID = c.ID, DisplayName = c.Displayname, Name = c.filename };
                        //    _files.Add(upf);
                        //    addFileToUI(upf);
                        //}
                    }
                };
                client.GetFilesAsync(entity.ID);
               
            }
        }

        private void SetExameType(Model.Silverlight.PublicOfficialInfo info)
        {
            int type = info.Type;
            switch (type)
            {
                case 0: rb0.IsChecked = true;
                    break;
                case 1: rb1.IsChecked = true;
                    break;
            }
            if (!string.IsNullOrEmpty(info.Infomation))
                rtb.SetXaml(info.Infomation);
           
        }

        private ObservableCollection<CommunitySystem.PublicOfficialSelectionService.ExameOrg> _orgs = null;
        private void GetExameType(Model.Silverlight.PublicOfficialInfo info)
        {
            if (rb0.IsChecked == true)
            {
                info.Type = 0;
               
            }
            else if (rb1.IsChecked == true)
            {
                info.Type = 1;
            }
            info.Infomation = rtb.GetXaml();
        }
        private UploadFileInfo _Xaml = null;
        private bool NeedToUpload = false;
        private int lenght = 2500;
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            NeedToUpload = false;
            tags.Clear();
            listfiles.Clear();
            BindingExpression beUsername = tbName.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            //int count = Validation.GetErrors().Count;
            if (errorCount > 0)//判断是否有验证失败
                return;
            GetExameType(entity);
            entity.Status = 1;
            //entity.InputTime = DateTime.Now;
            //client.SavePublicOfficialInfoAsync(CommunitySystem.Model.Silverlight.EntityConvertor.Convert
            //    <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity));
            entity.InputTime = DateTime.Now;
            _entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity);
            _entity.Orgs = _orgs;
            client.ShiFouYouFaBuZhiWeiAsync(_entity.ID);
        }
        void client_ShiFouYouFaBuZhiWeiCompleted(object sender, PublicOfficialSelectionService.ShiFouYouFaBuZhiWeiCompletedEventArgs e)
        {
            if (e.Result == false)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("该考试没有发布职位，不可发布！");
            }
            else
            {
                //验证是有已有考试处于发布状态
                client.ChechIsPublishAsync(_entity.ID);
            }
        }

        void client_ChechIsPublishCompleted(object sender, PublicOfficialSelectionService.ChechIsPublishCompletedEventArgs e)
        {
            if (e.Result == false)
            {
                //foreach (var f in _files)
                //{
                //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                //    if (f.Context != null && f.Context.Count > 0)
                //    {
                //        client.UploadFileAsync("file", f.Name, f.Context[0], true, f);
                //        f.Context.RemoveAt(0);
                //        tags.Add(f, false);
                //    }
                //    listfiles.Add(_f);
                //}
                if (_files1 != null && _files1.Count != 0)
                {
                    if (_files1.Where(p => p.State == Constants.FileStates.Pending).Count() > 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("您所选的附件还未上传，请点击上传进行上传！");
                        return;
                    }
                    if (_files1.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
                        return;
                    }
                    else
                    {

                        foreach (var item in _files1.Where(p => p.State == Constants.FileStates.Finished).ToList())
                        {

                            //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                            var att = new CommunitySystem.PublicOfficialSelectionService.Files() { Displayname = item.FileNameG, filename = item.FileName, ParentTableKey = entity.ID, InputDate = DateTime.Now, Status = (item.State).ToString(), FileSize = item.FileSize.ToString(), Percentage = item.Percentage.ToString() };
                            listfiles.Add(att);
                        }

                    }
                }
                if (tags.Count == 0)
                {
                    //if (NeedToUpload == true)
                    //{
                    //    client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], true, _Xaml);
                    //    _Xaml.UploadString.RemoveAt(0);
                    //}
                    //else
                    //{
                        client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                    //}
                }
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("已有考试处于发布状态，不能发布，请先锁定已发布考试");
            }
            
        }

       

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo _entity = null;

        private Dictionary<UploadFileInfo, bool> tags = new Dictionary<UploadFileInfo, bool>();
        private ObservableCollection<CommunitySystem.PublicOfficialSelectionService.Files> listfiles = new ObservableCollection<PublicOfficialSelectionService.Files>();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NeedToUpload = false;
            tags.Clear();
            listfiles.Clear();
            BindingExpression beUsername = tbName.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            //int count = Validation.GetErrors().Count;
            if (errorCount > 0)//判断是否有验证失败
                return;
            GetExameType(entity);
            entity.Status = 0;
            entity.InputTime = DateTime.Now;
            _entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity);
            _entity.Orgs = _orgs;


            //foreach (var f in _files)
            //{
            //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
              
            //    if ( f.Context != null &&f.Context.Count > 0)
            //    {
            //        client.UploadFileAsync("file", f.Name, f.Context[0], true, f);
            //        f.Context.RemoveAt(0);
            //        tags.Add(f, false);
            //    }
            //    listfiles.Add(_f);
            //}
            if (_files1 != null && _files1.Count != 0)
            {
                if (_files1.Where(p => p.State == Constants.FileStates.Pending).Count() > 0)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("您所选的附件还未上传，请点击上传进行上传！");
                    return;
                }
                if (_files1.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
                    return;
                }
                else
                {

                    foreach (var item in _files1.Where(p => p.State == Constants.FileStates.Finished).ToList())
                    {

                        //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                        var att = new CommunitySystem.PublicOfficialSelectionService.Files() { Displayname = item.FileNameG, filename = item.FileName, ParentTableKey = entity.ID, InputDate = DateTime.Now, Status = (item.State).ToString(), FileSize = item.FileSize.ToString(), Percentage = item.Percentage.ToString() };
                        listfiles.Add(att);
                    }

                }
            }
            if (tags.Count == 0)
            {
                //if (NeedToUpload == true)
                //{
                //    client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], true, _Xaml);
                //    _Xaml.UploadString.RemoveAt(0);
                //}
                //else
                //{
                    client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                //}
               
            }
            
            
        }

        private void OverButton_Click(object sender, RoutedEventArgs e)
        {
            NeedToUpload = false;
            tags.Clear();
            listfiles.Clear();
            BindingExpression beUsername = tbName.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            //int count = Validation.GetErrors().Count;
            if (errorCount > 0)//判断是否有验证失败
                return;
            GetExameType(entity);
            entity.Status = 3;
            entity.InputTime = DateTime.Now;
            _entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity);
            _entity.Orgs = _orgs;


            //foreach (var f in _files)
            //{
            //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };

            //    if (f.Context != null && f.Context.Count > 0)
            //    {
            //        client.UploadFileAsync("file", f.Name, f.Context[0], true, f);
            //        f.Context.RemoveAt(0);
            //        tags.Add(f, false);
            //    }
            //    listfiles.Add(_f);
            //}
            if (_files1 != null && _files1.Count != 0)
            {
                if (_files1.Where(p => p.State == Constants.FileStates.Pending).Count() > 0)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("您所选的附件还未上传，请点击上传进行上传！");
                    return;
                }
                if (_files1.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
                    return;
                }
                else
                {

                    foreach (var item in _files1.Where(p => p.State == Constants.FileStates.Finished).ToList())
                    {

                        //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                        var att = new CommunitySystem.PublicOfficialSelectionService.Files() { Displayname = item.FileNameG, filename = item.FileName, ParentTableKey = entity.ID, InputDate = DateTime.Now, Status = (item.State).ToString(), FileSize = item.FileSize.ToString(), Percentage = item.Percentage.ToString() };
                        listfiles.Add(att);
                    }

                }
            }
            if (tags.Count == 0)
            {
                //if (NeedToUpload == true)
                //{
                //    client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], true, _Xaml);
                //    _Xaml.UploadString.RemoveAt(0);
                //}
                //else
                //{
                    client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                //}

            }


        }

        void client_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            UploadFileInfo f = e.UserState as UploadFileInfo;

            if (f.Context.Count == 0)
            {
                tags[f] = true;
                int count = tags.Values.Where(c => c == false).Count();
                if (count == 0)
                {
                    
                    if (NeedToUpload == true)
                    {
                        client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], false, _Xaml);
                        _Xaml.UploadString.RemoveAt(0);
                    }
                    else
                    {
                        client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                    }
                    return;
                }
            }
            else
            {
                client.UploadFileAsync("file", f.Name, f.Context[0], false, f);
                f.Context.RemoveAt(0);
            }




        }
        
        private ObservableCollection<UploadFileInfo> _files = new ObservableCollection<UploadFileInfo>();
        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void HyperlinkButton_Click(object sender, System.Windows.RoutedEventArgs e)
        //{

        //    var filesDialog = new OpenFileDialog() { Multiselect = false };

        //    if (filesDialog.ShowDialog() == false)
        //        return;

        //    //var s = files.FullName;

        //    // 文件内容
        //    System.IO.Stream stream = filesDialog.File.OpenRead();



        //    UploadFileInfo uploadFile = new UploadFileInfo() { DisplayName = filesDialog.File.Name, Name = Guid.NewGuid().ToString() };
        //    uploadFile.Size = stream.Length / 1024.00;
        //    uploadFile.Context = new List<byte[]>();
        //    int b = 0;
           
        //    while (stream.Position > -1 && stream.Position < stream.Length)
        //    {
        //        if (stream.Length - stream.Position >= 16000)
        //        {
        //            b = 16000;
        //        }
        //        else
        //        {
        //            b = (int)(stream.Length - stream.Position);
        //        }

        //        byte[] filebyte = new byte[b];
        //        stream.Read(filebyte, 0, b);
        //        uploadFile.Context.Add(filebyte);
        //    }
        //    stream.Close();
        //    if (uploadFile.Context.Count > 0)
        //    {
        //        _files.Add(uploadFile);
        //        addFileToUI(uploadFile);
        //    }
            
           
        //}

        private void addFileToUI(UploadFileInfo uploadFile)
        {
            //Border border = new Border() { BorderThickness = new Thickness(1, 1, 1, 1), BorderBrush = new SolidColorBrush(Colors.Red), Margin = new Thickness(5, 2, 0, 0) };
            //StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
            //TextBlock tb = new TextBlock() { Text = uploadFile.DisplayName, Margin = new Thickness(5, 0, 0, 0) };
            //sp.Children.Add(tb);
            //HyperlinkButton hlb = new HyperlinkButton() { Content = "×", Margin = new Thickness(2, 0, 0, 0), Foreground = new SolidColorBrush(Colors.Red), Tag = border, Name = uploadFile.Name };
            //hlb.Click += new RoutedEventHandler(hlb_Click);
            //sp.Children.Add(hlb);
            //border.Child = sp;
            //wp.Children.Add(border);
            //读取指定大小的文件流内容到uploadFile.Context以便上传
           
           
        }

        void hlb_Click(object sender, RoutedEventArgs e)
        {
            //HyperlinkButton hlb = sender as HyperlinkButton;
            //Border b = hlb.Tag as Border;
            //if (b != null)
            //    wp.Children.Remove(b);
            //string name = hlb.Name;
            //_files.Remove(_files.Where(c => c.Name == name).FirstOrDefault());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click2(object sender, System.Windows.RoutedEventArgs e)
        {
        	// 在此处添加事件处理程序实现。
            OrgSelectWindow window = new OrgSelectWindow(_orgs);
            window.Show();
            window.Closed -= new EventHandler(window_Closed);
            window.Closed += new EventHandler(window_Closed);
			
        }

        void window_Closed(object sender, EventArgs e)
        {
            OrgSelectWindow window = sender as OrgSelectWindow;
            if (window.DialogResult == true)
            {
                _orgs = window._orgs;
            }
        }

       

        private void ModelRadioButton_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb != null)
            {
                switch (rb.Name)
                {
                    case "edit":
                        rtb.EditorStatus = Beetle.Sl.EditorControl.Core.EditorStatusEnum.Edit;
                        break;
                    case "design":
                        rtb.EditorStatus = Beetle.Sl.EditorControl.Core.EditorStatusEnum.Designer;
                        break;
                    case "preView":
                        var content = rtb.GetZipBytes();
                        RTBPreViewWindow win = new RTBPreViewWindow(content);
                        win.Show();
                        break;
                }
            }
        }

        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            NeedToUpload = false;
            tags.Clear();
            listfiles.Clear();
            BindingExpression beUsername = tbName.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            //int count = Validation.GetErrors().Count;
            if (errorCount > 0)//判断是否有验证失败
                return;
            GetExameType(entity);
            entity.Status = 2;
            entity.InputTime = DateTime.Now;
            _entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity);
            _entity.Orgs = _orgs;

            if (vidata())
            {
                //foreach (var f in _files)
                //{
                //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };

                //    if (f.Context != null && f.Context.Count > 0)
                //    {
                //        client.UploadFileAsync("file", f.Name, f.Context[0], true, f);
                //        f.Context.RemoveAt(0);
                //        tags.Add(f, false);
                //    }
                //    listfiles.Add(_f);
                //}
                if (_files1 != null && _files1.Count != 0)
                {
                    if (_files1.Where(p => p.State == Constants.FileStates.Pending).Count() > 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("您所选的附件还未上传，请点击上传进行上传！");
                        return;
                    }
                    if (_files1.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
                        return;
                    }
                    else
                    {
                       
                          foreach (var item in _files1.Where(p => p.State == Constants.FileStates.Finished).ToList())
                        {

                            //    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                            var att = new CommunitySystem.PublicOfficialSelectionService.Files() { Displayname = item.FileNameG, filename = item.FileName, ParentTableKey = entity.ID, InputDate = DateTime.Now, Status = (item.State).ToString(), FileSize = item.FileSize.ToString(), Percentage = item.Percentage.ToString() };
                            listfiles.Add(att);
                        }
                      
                    }
                }
                if (tags.Count == 0)
                {
                    //if (NeedToUpload == true)
                    //{
                    //    client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], true, _Xaml);
                    //    _Xaml.UploadString.RemoveAt(0);
                    //}
                    //else
                    //{
                        client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                    //}

                }
            }
            
        }
        private bool vidata()
        {
            if (string.IsNullOrEmpty(_entity.Name))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入考试名称！");
                return false;
            }
            if (string.IsNullOrEmpty(_entity.Office))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入招考发布单位！");
                return false;
            }
            if (_entity.YM==null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入时间！");
                return false;
            }
            return true;
        }

        private int _maxFileSize = int.MaxValue;

        private FileCollection _files1;
        private int _maxUpload = 4;
        private string _customParams;
        private string _fileFilter;

        public void Page(IDictionary<string, string> initParams)
        {
            _files1 = new FileCollection(_customParams, _maxUpload);
            if (GetFiles != null)
            {
                //if (entity.Attachment != null)
                //{
                if (GetFiles.Count > 0)
                {
                    foreach (var item in GetFiles)
                    {
                        var uf = new UserFile() { FileName = item.filename, FileNameG = item.Displayname, State = Constants.FileStates.Finished, Percentage = Convert.ToInt32(item.Percentage), BytesUploaded = Convert.ToDouble(item.FileSize), FileSize = Convert.ToDouble(item.FileSize) };

                        _files1.Add(uf);
                    }
                }
                //}
            }

            FileList.ItemsSource = _files1;

        }
        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {

            //var filesDialog = new OpenFileDialog() { Multiselect = false };

            //if (filesDialog.ShowDialog() == false)
            //    return;

            ////var s = files.FullName;

            //// 文件内容
            //System.IO.Stream stream = filesDialog.File.OpenRead();



            //UploadFileInfo uploadFile = new UploadFileInfo() { DisplayName = filesDialog.File.Name, Name = Guid.NewGuid().ToString() };
            //uploadFile.Size = stream.Length / 1024.00;
            //uploadFile.Context = new List<byte[]>();
            //int b = 0;

            //while (stream.Position > -1 && stream.Position < stream.Length)
            //{
            //    if (stream.Length - stream.Position >= 16000)
            //    {
            //        b = 16000;
            //    }
            //    else
            //    {
            //        b = (int)(stream.Length - stream.Position);
            //    }

            //    byte[] filebyte = new byte[b];
            //    stream.Read(filebyte, 0, b);
            //    uploadFile.Context.Add(filebyte);
            //}
            //stream.Close();
            //if (uploadFile.Context.Count > 0)
            //{
            //    _files.Add(uploadFile);
            //    addFileToUI(uploadFile);
            //}

            #region
            if (_files1 != null)
                _files1.Clear();

            OpenFileDialog ofd = new OpenFileDialog() { Multiselect = false };

            try
            {
                if (!string.IsNullOrEmpty(_fileFilter))
                    ofd.Filter = _fileFilter;
            }
            catch (ArgumentException ex)
            {
                //User supplied a wrong configuration file
                throw new Exception("Wrong file filter configuration.", ex);
            }

            if (ofd.ShowDialog() == true)
            {

                foreach (FileInfo file in ofd.Files)
                {
                    string GuidName = Guid.NewGuid().ToString("N");
                    string fileName = file.Name;

                    UserFile userFile = new UserFile();
                    userFile.FileName = GuidName; //GuidName file.Name;
                    userFile.FileNameG = fileName;
                    userFile.IsAdd = true;
                    userFile.FileStream = file.OpenRead();


                    #region  页面显示
                    foreach (var item in _files1)
                    {
                        if (item.FileNameG.Contains(fileName))
                        {
                            SilverlightMessageBoxLibrary.CustomMessage cm = new SilverlightMessageBoxLibrary.CustomMessage("此文件已上传,需要覆盖原有文件吗?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
                            cm.Show();
                            cm.OKButton.Click += (sender1, e1) =>
                            {
                                _files1.Remove(item);
                            };
                        }
                    }
                    #endregion

                    if (userFile.FileStream.Length <= _maxFileSize)
                    {
                        //向文件列表中添加文件信息
                        if (_files1 == null) _files1 = new FileCollection(_customParams, _maxUpload);
                        _files1.Add(userFile);
                    }
                    else
                        SilverlightMessageBoxLibrary.Message.InfoMessage("上传最大文件大小：" + (_maxFileSize / 1024).ToString() + "KB.");
                }
            }
            #endregion
        }

        private void btnsC_Click(object sender, RoutedEventArgs e)
        {
            if (_files1.Count == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择上传的附件！");
                return;
            }
            else
            {

                _files1.UploadFiles();
            }
        }
    }
}

